import {setToken, removeToken} from '/src/utils/auth.js'
import {setStore, getStore} from '/src/utils/store.js'
import {encryption, deepClone} from '/src/utils/util.js'
import {validatenull, isURL} from '/src/utils/validate.js'
import {formatPath} from '/src/router/avue-router.js'
import {defineStore} from "pinia";
import {useNavsStore} from "./tags.js";
import {useCommonStore} from "./common.js";
import {authApi} from "../../api/auth.js";
import {ElMessage} from 'element-plus';
import erpMenu from '/src/router/modules/index.js'
import pageMenu from '/src/router/page/index.js'
import viewMenu from '/src/router/views/index.js'
import {ref} from "vue"


export const useUserStore = defineStore('user', () => {

  const userInfo = ref(getStore({name: 'userInfo'}) || {})
  const permission = ref(getStore({name: 'permission'}) || {})
  const roles = ref([])
  const menuId = ref({})
  const menu = ref(getStore({name: 'menu'}) || [])
  const menuAll = ref(getStore({name: 'menuAll'}) || [])
  const token = ref(getStore({name: 'token'}) || '')
  const refreshToken = ref(getStore({name: 'refreshToken'}) || '')
  const tenantId = ref(getStore({name: 'tenantId'}) || '')


  //根据用户名登录
  async function LoginByUsername(userInfo = {}) {
    return new Promise((resolve, reject) => {
      authApi.loginByUsername(userInfo.tenantId, userInfo.username, userInfo.password, userInfo.type, userInfo.key, userInfo.code).then(res => {
        const data = res.data.data;
        SET_TOKEN(data.access_token); //设置access_token
        SET_REFRESH_TOKEN(data.refresh_token);  //设置refresh_token
        SET_TENANT(userInfo.tenantId);
        const navsStore = useNavsStore()
        navsStore.DEL_ALL_TAG([]); //删除所有tag
        const commonStore = useCommonStore()
        commonStore.CLEAR_LOCK();  //清除锁定状态
        resolve();
      }).catch(error => {
        reject(error);
      })
    })
  }

  async function GetCurrentUserInfo() {
    return new Promise((resolve, reject) => {
      authApi.getCurrentUserInfo().then(res => {
        const data = res.data.data;
        SET_USER_INFO(data);
        resolve();
      }).catch(error => {
        reject(error);
      })
    })
  }

  //根据第三方信息登录
  async function LoginBySocial(userInfo) {
    return new Promise((resolve) => {
      authApi.loginBySocial(userInfo.tenantId, userInfo.source, userInfo.code, userInfo.state).then(res => {
        const data = res.data;
        if (data.success) {
          SET_TOKEN(data.data.accessToken);
          SET_REFRESH_TOKEN(data.data.refreshToken);
          SET_USER_INFO(data.data);
          DEL_ALL_TAG();
          CLEAR_LOCK();
        } else {
          ElMessage({
            type: 'error',
            message: data.msg
          })
        }
        resolve();
      })
    })
  }

  //根据手机号登录
  async function LoginByPhone(userInfo) {
    return new Promise((resolve) => {
      authApi.loginByUsername(userInfo.phone, userInfo.code).then(res => {
        const data = res.data.data;
        SET_TOKEN(data);
        const navsStore = useNavsStore()
        navsStore.DEL_ALL_TAG([]);
        CLEAR_LOCK();
        resolve();
      })
    })
  }

  async function GetUserInfo() {
    return new Promise((resolve, reject) => {
      authApi.getUserInfo().then((res) => {
        const data = res.data.data;
        SET_USER_INFO(data.userInfo);
        SET_ROLES(data.roles);
        SET_PERMISSION(data.permission)
        resolve(data);
      }).catch(err => {
        reject(err);
      })
    })
  }

  //刷新token
  async function RefreshToken() {
    return new Promise((resolve, reject) => {
      setStore({name: 'refreshFlag', content: true, type: 'session'});
      authApi.refreshToken(refreshToken.value, tenantId.value).then(res => {
        const data = res.data.data;
        SET_REFRESH_TOKEN(data.refreshToken);
        resolve(data);
      }).catch(error => {
        reject(error)
      })
    })
  }

  //刷新token
  //使用续签token的方式，结合后端的token自动续签，保证只要系统登录了，就一直登录着。防止接警端长期不操作，导致的断线。
  async function RenewToken() {
    return new Promise((resolve, reject) => {
      authApi.renewToken().then(res => {
        resolve(res);
      }).catch(error => {
        reject(error)
      })
    })
  }

  // 登出
  async function LogOut() {
    return new Promise((resolve, reject) => {
      authApi.logout().then(() => {
        // 清空token
        SET_TOKEN('')
        // 清空refresh token
        SET_REFRESH_TOKEN('');
        // 清空menuALL
        SET_MENU_ALL_NULL([]);
        // 清空menu
        SET_MENU([])
        // 清空角色
        SET_ROLES([])
        // 清空所有的tag
        const navsStore = useNavsStore()
        navsStore.DEL_ALL_TAG([]);
        // 清空锁屏
        const commonStore = useCommonStore()
        commonStore.CLEAR_LOCK();
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }

  //注销session
  async function FedLogOut() {
    return new Promise(resolve => {
      // 清空token
      SET_TOKEN('')
      // 清空refresh token
      SET_REFRESH_TOKEN('');
      // 清空menuALL
      SET_MENU_ALL_NULL([]);
      // 清空menu
      SET_MENU([])
      // 清空角色
      SET_ROLES([])
      // 清空所有的tag
      const navsStore = useNavsStore()
      navsStore.DEL_ALL_TAG([]);
      // 清空锁屏
      const commonStore = useCommonStore()
      commonStore.CLEAR_LOCK();
      removeToken()
      resolve()
    })
  }

  //获取顶部的菜单
  async function GetTopMenu() {
    return new Promise(resolve => {
      authApi.getTopMenu().then((res) => {
        const data = res.data || []
        resolve(data)
      })
    })
  }

  //获取系统菜单
  async function GetAuthMenu() {
    return new Promise(resolve => {
      authApi.getAuthMenu().then((res) => {
        const data = res.data.data;
        let menu = deepClone(data.menuList);
        // todo whf 可以在这里添加一个开关，是否启用本地菜单
        const commonStore = useCommonStore();
        if (commonStore.isUseLocalMenu) {
          // menu.push(...erpMenu)
          // menu.push(...viewMenu)
          // menu.push(...pageMenu)
        }

        menu.forEach(ele => {
          formatPath(ele, true);
        })
        SET_MENU(menu)
        SET_MENU_ALL(menu)
        // GetButtons();
        console.log("data.auth", data.auth)
        SET_PERMISSION(data.auth);
        resolve(menu)
      })
    })
  }



  function SET_TOKEN(newToken) {
    setToken(newToken)
    token.value = newToken;
    setStore({name: 'token', content: token.value, type: 'session'})
  }

  function SET_REFRESH_TOKEN(newToken) {
    refreshToken.value = newToken;
    setStore({name: 'refreshToken', content: refreshToken.value, type: 'session'})
  }

  function SET_TENANT(newTenantId) {
    tenantId.value = newTenantId;
    setStore({name: 'tenantId', content: tenantId.value, type: 'session'})
  }

  function SET_USER_INFO(newUserInfo) {
    userInfo.value = newUserInfo;
    setStore({name: 'userInfo', content: userInfo.value})
  }

  function SET_MENU_ID(newMenuId) {
    menuId.value = newMenuId;
  }

  function SET_MENU_ALL(newMenuAll) {
    let menu = menuAll.value;
    // 和现有的menuAll比较，没有的添加进来
    newMenuAll.forEach(ele => {
      let index = menu.findIndex(item => item.path == ele.path)
      if (index == -1) {
        menu.push(ele);
      } else {
        menu[index] = ele;
      }
    })
    menuAll.value = menu
    setStore({name: 'menuAll', content: menuAll.value, type: 'session'})
  }

  function SET_MENU_ALL_NULL() {
    menuAll.value = []
    setStore({name: 'menuAll', content: menuAll.value})
  }

  function SET_MENU(newMenuValue) {
    // step1 处理menu
    menu.value = newMenuValue
    setStore({name: 'menu', content: menu.value})

    // step2 处理menuAll
    if (validatenull(newMenuValue)) {
      return;
    }
    //合并动态路由去重
    // 可以使用上么的findIndex来优化，但是这里多了一个去重的功能
    let menuAll1 = menuAll.value;
    menuAll1 = menuAll1.concat(newMenuValue).reverse();
    let newMenu = [];
    for (let item1 of menuAll1) {
      let flag = true;
      for (let item2 of newMenu) {
        if (item1.name === item2.name || item1.path === item2.path) {
          flag = false;
        }
      }
      if (flag) {
        newMenu.push(item1);
      }
    }
    menuAll.value = newMenu;
    setStore({name: 'menuAll', content: menuAll.value, type: 'session'})
  }

  function SET_ROLES(newRoles) {
    roles.value = newRoles;
  }

  function SET_PERMISSION(newPermission) {
    let result = [];

    console.log("permission", newPermission)

    function getCode(list) {
      console.log("list", list)
      list.forEach(ele => {
        if (typeof (ele) === 'object') {
          const children = ele.children;
          const code = ele.code;
          if (children) {
            getCode(children)
          } else {
            result.push(code);
          }
        }
      })
    }

    console.log("permission", newPermission)
    // getCode(newPermission);
    // permission.value = {};
    // result.forEach(ele => {
    //   permission.value[ele] = true;
    // });
    permission.value = newPermission
    setStore({name: 'permission', content: permission.value, type: 'session'})
  }


  return {
    userInfo,
    permission,
    roles,
    menuId,
    menu,
    menuAll,
    token,
    refreshToken,
    tenantId,
    LoginByUsername,
    GetCurrentUserInfo,
    LoginBySocial,
    LoginByPhone,
    GetUserInfo,
    RefreshToken,
    RenewToken,
    LogOut,
    FedLogOut,
    GetTopMenu,
    GetAuthMenu,
    SET_TOKEN,
    SET_REFRESH_TOKEN,
    SET_TENANT,
    SET_USER_INFO,
    SET_MENU_ID,
    SET_MENU_ALL,
    SET_MENU_ALL_NULL,
    SET_MENU,
    SET_ROLES,
    SET_PERMISSION,

  }
})
